//
//  CGMineViewController.m
//  SchoolClient
//
//  Created by mac on 15/10/27.
//  Copyright © 2015年 mac. All rights reserved.
///   http://180.150.226.223/SchoolApp-Service/upload/userlogo/39.jpg

#import "CGMineViewController.h"


@interface CGMineViewController ()<UIImagePickerControllerDelegate,UIActionSheetDelegate,UINavigationControllerDelegate,UITextFieldDelegate>

@property(nonatomic,strong)UIImageView *headerImage;
@property(nonatomic,strong)UIImage *headerIcon;

@end

//定义一个图片的分类
@implementation UIImage (ProductLogo)
//在内存中绘图
- (UIImage *)rectangleImage
{
    
    CGFloat imageWidth = self.size.width;
    CGFloat imageHeight = self.size.height;
    CGFloat rectWidth = 60;   //60个点，对应120个像素
    CGFloat rectHeight = 60;
    //1.创建内存中的图片大小:位图大小为120X120，背景完全透明，缩放因子为0(即图片存储的位置)
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(rectWidth, rectHeight), NO, 0.0);
    //2.获取向内存中图片执行绘图的上下文:一个不透明类型的Quartz 2D绘画环境,可以拿画笔在上面任意绘画
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    //Calculate the scale factor 计算缩放因子
    CGFloat scaleFactorX = rectWidth/imageWidth;
    CGFloat scaleFactorY = rectHeight/imageHeight;
    
    CGContextScaleCTM (context, scaleFactorX, scaleFactorY);
    
    //把整张图片画进画布
    CGRect myRect = CGRectMake(0, 0, imageWidth, imageHeight);
    [self drawInRect:myRect];
    //3.得到内存中的图片，大小即UIGraphicsBeginImageContext(size)中size的大小
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    //NSLog(@"image:%@",NSStringFromCGSize(newImage.size));
    UIGraphicsEndImageContext();
    
    return newImage;
}

@end


@implementation CGMineViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [Tools getColor:@"ebebeb"];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"navigationbar_setting"] style:UIBarButtonItemStylePlain target:self action:@selector(settingAccount)];
    
    [self initTableView];
    [self initHeaderView];

    //使cell的线条充满
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
        
    }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
        
    }

}


#pragma mark 是否进入登录界面
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self initHeaderView];
    [self.tableView reloadData];
}

-(void)initTableView{
    
    CGRect aRect = CGRectMake(0,
                              0,
                              SCREEN_WIDTH,
                              SCREEN_HEIGHT-49.0-64.0);
    self.tableView = [[UITableView alloc] initWithFrame:aRect  style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    self.tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    self.tableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview: self.tableView];
}

-(void)initHeaderView{
    
    //表格头视图
    CGRect bRect = CGRectMake(0, 0, SCREEN_WIDTH, 100);
    UIView *headerView = [[UIView alloc]initWithFrame:bRect];
    headerView.backgroundColor = [UIColor whiteColor];
    self.tableView.tableHeaderView = headerView;
    //头像
    bRect.origin.x = 10;
    bRect.origin.y = 10;
    bRect.size.width = 80;
    bRect.size.height = 80;
    self.headerImage = [[UIImageView alloc]initWithFrame:bRect];
    self.headerImage.layer.cornerRadius = 40;
    //self.headerImage.layer.borderWidth = 2;
    //self.headerImage.layer.borderColor = [UIColor grayColor].CGColor;
    self.headerImage.layer.masksToBounds = YES; //设置超过子图层的部分裁减掉
    //把沙盒中的图片取出更新头像
    
    if (self.headerIcon) {
        
        self.headerImage.image = self.headerIcon;
        
    }else{
        self.headerIcon = nil;
        CGAccountDefault *defaultAccount = [CGAccountDefault shareAccount];
        if (defaultAccount.headerIconPath.length != 0) {
            NSLog(@"%@",defaultAccount.headerIconPath);
            NSURL *url = [NSURL URLWithString:[CGAccountDefault shareAccount].headerIconPath];
            
            [self performSelectorInBackground:@selector(downloadHeaderIcon:) withObject:url];
            
        }else{
            self.headerImage.image = [UIImage imageNamed:@"mine_face"];
        }
    
    }
   
    [headerView addSubview:self.headerImage];

    
    //右箭头
    bRect.origin.x = SCREEN_WIDTH - 20;
    bRect.origin.y = 44;
    bRect.size.height = 12;
    bRect.size.width = 12*16/31;
    UIImageView *arrowImageView = [[UIImageView alloc]initWithFrame:bRect];
    arrowImageView.image = [UIImage imageNamed:@"mine_arrow_right"];
    [headerView addSubview:arrowImageView];
    
    //个人信息Label
    bRect.origin.x = SCREEN_WIDTH - 100;
    bRect.origin.y = 40;
    bRect.size.width = 70;
    bRect.size.height = 20;
    UILabel *personalMessagelabel = [[UILabel alloc]initWithFrame:bRect];
    personalMessagelabel.text = @"个人信息";
    personalMessagelabel.font = [UIFont systemFontOfSize:13];
    personalMessagelabel.textAlignment = NSTextAlignmentRight;
    [headerView addSubview:personalMessagelabel];
   
    //添加编辑个人信息按钮
    UIButton *infoButton = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH - 120, 0, 120, 100)];
    infoButton.backgroundColor = [UIColor clearColor];
    [headerView addSubview:infoButton];
    [infoButton addTarget:self action:@selector(editPersonalInfo) forControlEvents:UIControlEventTouchUpInside];
    
    //添加更改图片按钮
    UIButton *imageButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
    imageButton.backgroundColor = [UIColor clearColor];
    [headerView addSubview:imageButton];
    [imageButton addTarget:self action:@selector(displayPopupView) forControlEvents:UIControlEventTouchUpInside];
    
    //添加姓名Label
    CGAccountDefault *user = [CGAccountDefault shareAccount];
    UILabel *nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(110, 40, 100, 20)];
    if (user.login) {
        nameLabel.text = user.name;
    }
    nameLabel.font = [UIFont systemFontOfSize:13];
    [headerView addSubview:nameLabel];
    
    //添加VIPLabel
    UILabel *VIPLabel = [[UILabel alloc]initWithFrame:CGRectMake(110, 60, 100, 20)];
    if (user.login && user.isVip) {
        VIPLabel.text = @"认证会员";
    }
    VIPLabel.textColor = [UIColor orangeColor];
    VIPLabel.font = [UIFont systemFontOfSize:13];
    [headerView addSubview:VIPLabel];
    
}


-(void)downloadHeaderIcon:(NSURL *)url{
    
    NSData *data = [NSData dataWithContentsOfURL:url];
    UIImage *image = [UIImage imageWithData:data];
    [self.headerImage performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:NO];
}


#pragma mark 进入账号设置界面
-(void)settingAccount{
    
    CGSettingViewController *settingVC = [CGSettingViewController new];
    settingVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:settingVC animated:YES];
}


#pragma mark 进入编辑个人信息
-(void)editPersonalInfo{
    
    CGAccountDefault *account = [CGAccountDefault shareAccount];
    if (account.login) {
        CGPersonInfoViewController *personInfoVC = [CGPersonInfoViewController new];
        personInfoVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:personInfoVC animated:YES];
        
    }else{
        CGLoginViewController *loginVC = [CGLoginViewController new];
        loginVC.hidesBottomBarWhenPushed = YES;
        //loginVC.fromHomeVC = YES;
        [self.navigationController pushViewController:loginVC animated:NO];
    }
}




#pragma mark 照相机或相片处理事件
//弹出ActionSheet选择框
-(void)displayPopupView{
    
    CGAccountDefault *account = [CGAccountDefault shareAccount];
    if (account.login) {
        
        UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:@"请选择相片来源" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"拍摄" otherButtonTitles:@"图片库", nil];
        [sheet showInView:self.view];
        
    }else{
        
        CGLoginViewController *loginVC = [CGLoginViewController new];
        loginVC.hidesBottomBarWhenPushed = YES;
        //loginVC.fromHomeVC = YES;
        [self.navigationController pushViewController:loginVC animated:NO];
    }
}

//ActionSheet回调方法
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (buttonIndex == 0) {
        [self gotoCamera];
    }else if (buttonIndex == 1) {
        [self gotoPhotoLibrary];
    }else{
        return;
    }
    
}

//跳转到照相功能
-(void)gotoCamera{
    
    //先设定sourceType为相机，然后判断相机是否可用（ipod）没相机，不可用将sourceType设定为相片库
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if (![UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }
    //sourceType = UIImagePickerControllerSourceTypeCamera; //照相机
    //sourceType = UIImagePickerControllerSourceTypePhotoLibrary; //图片库
    //sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum; //保存的相片
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];//创建图像选取控制器
    picker.delegate = self;
    picker.allowsEditing = YES;                                              //设置可编辑
    picker.sourceType = sourceType;
    [self presentViewController:picker animated:YES completion:nil];         //进入照相界面
}

//跳转到系统相册文件夹
-(void)gotoPhotoLibrary{
    
    UIImagePickerController *picker = [UIImagePickerController new];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentViewController:picker animated:YES completion:nil];
    
}

//image picker delegte回调方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    
    //[self dismissViewControllerAnimated:YES completion:nil];
    [picker.presentingViewController dismissViewControllerAnimated:YES completion:nil];
    //1.把字典里的图片取出来修改后返回
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:info];
    dic[UIImagePickerControllerEditedImage] = [dic[UIImagePickerControllerEditedImage] rectangleImage];
    info = [NSDictionary dictionaryWithDictionary:dic];
    //2.把修改后的图片取出来更新UI
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    self.headerImage.image = image;
    self.headerIcon = image;
    //3.转换图片的格式为二进制
    NSData *imageData = UIImageJPEGRepresentation(image, 1);

    //4.把图片上传到服务器
    CGAccountDefault *account = [CGAccountDefault shareAccount];
    NSDictionary *paramDic = @{@"account":account.account,@"password":account.password,@"file":@"data"};
    
    ZYHRequest *request = [ZYHRequest new];
    [request postAsyncImageRequest:@"/upload/uploadUserLogo.app" headImage:imageData parameters:paramDic success:^(id responseData) {
        
        NSLog(@"上传头像成功！");
        NSString *result = [[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
        //NSLog(@"result:%@",result);
        if ([result rangeOfString:@"imgPath"].location != NSNotFound) {
            CGAccount *user = [CGAccount objectWithJSONData:responseData];
            account.headerIconPath = [NSString stringWithFormat:@"%@%@",BASE_URL,user.imgPath];
            [account saveToSandBox];
        }
        
    } failure:^(NSError *error) {
        
        NSLog(@"error:%@",error);
    }];
    

}


#pragma mark 重写表格的代理方法

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (section == 0) {
        CGAccountDefault *account = [CGAccountDefault shareAccount];
        if (!account.isVip) {
            return 5;
        }else{
            return 4;
        }
    }else{
        return 2;
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"tableviewCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
        cell.textLabel.font = [UIFont systemFontOfSize:15];
    }
    
    if (indexPath.section == 0) {
        switch (indexPath.row) {
            case 0:
                cell.imageView.image = [UIImage imageNamed:@"mine_collect_icon"];
                cell.textLabel.text = @"信息收藏";
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                break;
            case 1:
                cell.imageView.image = [UIImage imageNamed:@"mine_message_notice_icon"];
                cell.textLabel.text = @"信息提醒";
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                break;
            case 2:
                cell.imageView.image = [UIImage imageNamed:@"mine_files_icon"];
                cell.textLabel.text = @"档案服务";
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                break;
            case 3:
                cell.imageView.image = [UIImage imageNamed:@"mine_files_check_icon"];
                cell.textLabel.text = @"档案查询";
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                break;
            default:
                cell.imageView.image = [UIImage imageNamed:@"mine_vip_icon"];
                cell.textLabel.text = @"认证会员";
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                break;
        }
        
    }else{
        switch (indexPath.row) {
            case 0:
                cell.imageView.image = [UIImage imageNamed:@"mine_views_icon"];
                cell.textLabel.text = @"意见反馈";
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                break;
            default:
                cell.imageView.image = [UIImage imageNamed:@"mine_contact_icon"];
                cell.textLabel.text = @"联系我们";
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                break;
        }
    }

    return cell;
}


//设置表头表尾高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 15;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    CGAccountDefault *account = [CGAccountDefault shareAccount];
    CGLoginViewController *loginVC = [CGLoginViewController new];
    //loginVC.fromHomeVC = YES;
    loginVC.hidesBottomBarWhenPushed = YES;

    BaseViewController *viewController;
    if (indexPath.section == 0) {
        switch (indexPath.row) {
            case 0:
                if (!account.login) {
                    [self.navigationController pushViewController:loginVC animated:NO];
                    return;
                }
                viewController = [CGFavoritesViewController new];
                break;
            case 1:
                viewController = [CGRemindingViewController new];
                break;
            case 2:
                viewController = [CGServiceViewController new];
                break;
            case 3:
                if (!account.login) {
                    [self.navigationController pushViewController:loginVC animated:NO];
                    return;
                }
                if (!account.isVip) {
                    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"该服务仅供认证会员使用" delegate:self cancelButtonTitle:@"狠心放弃" otherButtonTitles:@"认证会员", nil];
                    [alertView show];
                    return;
                }
                viewController = [CGQueryingViewController new];
                break;
            default:
                if (!account.login) {
                    [self.navigationController pushViewController:loginVC animated:NO];
                    return;
                }
                viewController = [CGPurchaseViewController new];
                break;
        }
        
    }else{
        switch (indexPath.row) {
            case 0:
                if (!account.login) {
                    [self.navigationController pushViewController:loginVC animated:NO];
                    return;
                }
                viewController = [CGSuggestionViewController new];
                break;
            default:
                viewController = [CGContactViewController new];
                break;
        }
    }
    
    viewController.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:viewController animated:YES];
    
}

#pragma mark alertView代理方法
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (buttonIndex == 1) {
        //跳转支付宝界面
        CGPurchaseViewController *purchaseVC = [CGPurchaseViewController new];
        purchaseVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:purchaseVC animated:YES];
    }
}

//使cell的线条充满
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

-(void)viewWillDisappear:(BOOL)animated{
    self.headerIcon = nil;
}

@end
